package com.kurumi.autoprint.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;

import com.itextpdf.io.font.FontProgram;
import com.itextpdf.io.font.FontProgramFactory;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;

public class FontManager {

	public static final String SimSun = "simsun";
	
	/**
	 * 获取宋体
	 * @return
	 */
	public static PdfFont getSimSunFont() throws Exception {
		PdfFont font = null;
		File file = ResourceUtils.getFile("classpath:simsun.ttf");
		InputStream stream = new FileInputStream(file);
		
		ByteArrayOutputStream output = null;
		byte[] buffer = null;
		
	    try {
	    	output = new ByteArrayOutputStream();
	    	buffer = new byte[4096];
	 	    int m = 0;
	 	    
			while (-1 != (m = stream.read(buffer))) {
			    output.write(buffer, 0, m);
			}
			
			FontProgram fontProgram = FontProgramFactory.createFont(output.toByteArray());
			font = PdfFontFactory.createFont(fontProgram, PdfEncodings.IDENTITY_H);
	    } catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != output) {
				output.close();
			}
			
			buffer = null;
		}
	    
		return font;
	}
}
